package net.hzlj.platform.enterprise.utils;

import android.text.TextUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * Created by Administrator on 2016/8/10 0010.
 */
public class StringUtils {

    public static boolean isEmpty(String o){
        if (o != null && o.length() > 0){
            return false;
        }
        return true;
    }

    public static boolean isNotEmpty(String o){
        return !isEmpty(o);
    }


    /**
     * 16进制字符串转换成数组
     *
     * @param hex
     * @return
     */
    public static byte[] hexStringTobyte(String hex) {
        int len = hex.length() / 2;
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    public static int toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

    /**
     * 数组转成16进制字符串
     *
     * @param b
     * @return
     */
    public static String toHexString(byte[] b) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            buffer.append(toHexString1(b[i]));
        }
        return buffer.toString();
    }

    public static String toHexString1(byte b) {
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1) {
            return "0" + s;
        } else {
            return s;
        }
    }

    /**
     * 十六进制字符串转换成字符串
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 字符串转换成十六进制字符串
     */
    public static String str2Hexstr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString();
    }

    /**
     * 16进制字符串分割成若干块，每块32个16进制字符，即16字节
     *
     * @param str
     * @return
     */
    public static String[] hexStr2StrArray(String str) {
        // 32个十六进制字符串表示16字节
        int len = 32;
        int size = str.length() % len == 0 ? str.length() / len : str.length()
                / len + 1;
        String[] strs = new String[size];
        for (int i = 0; i < size; i++) {
            if (i == size - 1) {
                String temp = str.substring(i * len);
                for (int j = 0; j < len - temp.length(); j++) {
                    temp = temp + "0";
                }
                strs[i] = temp;
            } else {
                strs[i] = str.substring(i * len, (i + 1) * len);
            }
        }
        return strs;
    }

    /**
     * 把16进制字符串压缩成字节数组，在把字节数组转换成16进制字符串
     *
     * @param
     * @return
     * @throws java.io.IOException
     */
    public static byte[] compress(byte[] data) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(data);
        gzip.close();
        return out.toByteArray();
    }

    /**
     * 把16进制字符串解压缩压缩成字节数组，在把字节数组转换成16进制字符串
     *
     * @param
     * @return
     * @throws java.io.IOException
     */
    public static byte[] uncompress(byte[] data) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    public static byte[] short2byte(short s) {
        byte[] size = new byte[2];
        size[0] = (byte) (s >>> 8);
        short temp = (short) (s << 8);
        size[1] = (byte) (temp >>> 8);

        // size[0] = (byte) ((s >> 8) & 0xff);
        // size[1] = (byte) (s & 0x00ff);
        return size;
    }

    public static short[] hexStr2short(String hexStr) {
        byte[] data = hexStringTobyte(hexStr);
        short[] size = new short[4];
        for (int i = 0; i < size.length; i++) {
            size[i] = getShort(data[i * 2], data[i * 2 + 1]);
        }
        return size;
    }

    public static short getShort(byte b1, byte b2) {
        short temp = 0;
        temp |= (b1 & 0xff);
        temp <<= 8;
        temp |= (b2 & 0xff);
        return temp;
    }

    /****
     * @Description 根据下载链接获取文件名字
     * @param url   "http://211.138.238.83:9000/hzjz/ImageFile/2016-07/20140916145819.jpg";
     * @return      20140916145819.jpg
     */
    public static String getFileNameFromUrl(String url){
        if (isNotEmpty(url) && url.startsWith("http")){
            return url.substring(url.lastIndexOf("/") + 1,url.length());
        }
        return null;
    }

    /***
     * 根据文件路径获取文件名称
     * @param path（/data/data/net.hzlj.platform.enterprise.changsha/files/147246276735720160831181032.jpeg）
     * @return 147246276735720160831181032.jpeg
     */
    public static String getFileNameFromPath(String path){
        if (isNotEmpty(path)){
            return path.substring(path.lastIndexOf("/") + 1,path.length());
        }
        return null;
    }

    /***
     * 根据文件路径获取无文件后缀名的文件名
     * @param path（147246276735720160831181032.jpeg）
     * @return
     */
    public static String getFileNameNoSuffixFromPath(String path){
        String name = getFileNameFromPath(path);
        if (isNotEmpty(name) && name.contains(".")){
            return name.substring(0,name.lastIndexOf("."));
        }
        return name;
    }

    /***
     * 根据文件路径获取无文件后缀名的文件名（20140916145819）
     * @param url（20140916145819.jpg）
     * @return
     */
    public static String getFileNameNoSuffixFromUrl(String url){
        String name = getFileNameFromUrl(url);
        if (isNotEmpty(name) && name.contains(".")){
            return name.substring(0,name.lastIndexOf("."));
        }
        return name;
    }

    /***
     * 获取网络资源后缀（.jpg）
     * @param url（20140916145819.jpg）
     * @return
     */
    public static String getSuffixNameFromUrl(String url){
        String fileName = getFileNameFromUrl(url);
        if (isNotEmpty(fileName)){
            return fileName.substring(fileName.lastIndexOf("."),fileName.length());
        }
        return null;
    }

    public static boolean isNumeric(String str){
        if (TextUtils.isEmpty(str)){
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }

    public static int toInt(String str){
        if (isNumeric(str)){
            return Integer.valueOf(str);
        }
        return 0;
    }

}
